import * as express from 'express'
import apiSV from '../services/apiSV';
import exportExcelSV from '../services/exportExcelSV';


let router = express.Router()

/** 项目评价列表 */
router.get('/getList', async (req, res, next) => {
  try {
    let params: any = {
      action: 'corpsurvey.offlinetrainingevaluate.list',
      sessionKey: req.t,
      companyID: req.companyId,
      targetType: req.query.targetType,
      trainingID: req.query.trainingId,
      pageSize: req.query.pageSize || 10,
      pageIndex: req.query.page || 1,
    }

    if (req.query.exportExcel) {
      /** 导出excel前进行权限判断 */
      let data = await req.hasPermission(req.companyId, 'MENU-CORPTRAINING')
      if (!data.status) {
        throw new M.errors.TipsError(data.msg)
      }
      params.ispaging = 'false'
    }

    let data = await apiSV(req.api.v4.get, params)
    if (req.query.exportExcel) {
      if (data.data.ml.items.length <= 0) {
        throw new M.errors.TipsError('该列表为空无法导出')
      }
      let fnameText = req.query.trainingName || '',
        dataHeaders = [],
        closKeyName = []
      switch (req.query.targetType) {
        case '0':
          fnameText = `${fnameText}---项目评价`
          dataHeaders = ["姓名", "账号", "部门", "评星", "评语"]
          closKeyName = ['realName', "userName", 'orgName', "star", "evaluate"]
          break;
        case '1':
          fnameText = `${fnameText}---课堂评价`
          dataHeaders = ["姓名", "账号", "部门", "课程名称", "评星", "评语"]
          closKeyName = ['realName', "userName", 'orgName', "targetName", "star", "evaluate"]
          break;
        default:
          throw new M.errors.TipsError("类型判断错误")
      }
      return exportExcelSV(req, res, next, {
        fnameText,
        filterText: '',
        dataHeaders,
        closKeyName,
        rowItem: data.data.ml.items,
      })
    } else {
      return res.json({ status: true, data: data.data.ml })
    }
  } catch (e) {
    next(e)
  }
})


/** 评价 */
router.post("/evaluateAdd", async (req, res, next) => {
  try {
    // 0：项目评价；1：课程评价；
    let data = await apiSV(req.api.v4.post, {
      action: 'corpsurvey.offlinetrainingevaluate.add',
      sessionKey: req.t,
      companyID: req.companyId,
      targetType: req.body.targetType,
      targetName: req.body.targetName,
      targetID: req.body.targetID,
      evaluate: req.body.evaluate,
      star: req.body.star,
      trainingID: req.body.trainingId
    })
    return res.json({ status: true, data: data.data.avg })
  } catch (e) {
    next(e)
  }
})

export default router
